<template>
  <div class="set_page">
    <div class="head">
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :action="uploadurl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        auto-upload
      >
        <template #trigger>
          <el-button type="warning" :icon="Plus" circle />
        </template>
        <div>
          <img
            :src="useStore.avatar"
            class="avatar"
            style="width: 60px; height: 60px; border-radius: 50%; background-color: black"
          />
          <el-input
            class="input"
            size="large"
            v-model="input"
            style="width: 550px"
            placeholder="填写游记标题"
            maxlength="48"
            autofocus
            show-word-limit
          />
        </div>
      </el-upload>
      <img :src="imageUrl" />
    </div>
    <div class="set">
      <h2>设置游记头图</h2>
      <p>图片建议选择尺寸大于1680px的高清大图，如相机原图</p>
    </div>
    <div class="main">
      <el-button
        type="success"
        plain
        @click="dialogFormVisible = true"
        style="margin-bottom: 10px; margin-left: 10px"
        >去完善其他信息</el-button
      >
      <FullContent @go-finish="gofinish" :contents="contents"></FullContent>
    </div>
    <el-dialog v-model="dialogFormVisible" title="更多信息" width="700">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="出发时间:">
          <el-date-picker
            v-model="formInline.date"
            type="date"
            clearable
            style="width: 150px"
            size="large"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="人物:">
          <el-select
            v-model="formInline.people"
            placeholder="选择出行人物"
            clearable
            style="width: 150px"
          >
            <el-option label="一个人" value="一个人" />
            <el-option label="情侣/夫妻" value="情侣/夫妻" />
            <el-option label="带孩子" value="带孩子" />
            <el-option label="家庭出游" value="家庭出游" />
            <el-option label="和朋友" value="和朋友" />
            <el-option label="和同学" value="和同学" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="人均花费/RMB:" style="width: 300px">
          <el-input v-model="formInline.money" clearable placeholder="输入花费" />
        </el-form-item>
        <el-form-item label="出行人数:" style="width: 300px">
          <el-input-number v-model="formInline.num" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="游记标签:" style="width: 300px">
          <div class="flex gap-2">
            <el-tag
              v-for="tag in dynamicTags"
              :key="tag"
              closable
              :disable-transitions="false"
              style="margin-right: 5px"
              @close="handleClose(tag)"
              type="warning"
              effect="light"
              round
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="InputRef"
              v-model="inputValue"
              class="w-20"
              size="small"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <el-button v-else class="button-new-tag" size="small" @click="showInput">
              + 新标签
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type {reqtype} from '@/api/strategy/type.ts'
import { write,update } from '@/api/strategy/index.ts'
import FullContent from '@/components/fullcontent/index.vue'
import {  Plus } from '@element-plus/icons-vue'
//引入用户相关的小仓库
import { useUserStore } from '@/stores/user'
let useStore = useUserStore()
import { ref, onMounted, nextTick, reactive } from 'vue'
let imageUrl = ref('https://t7.baidu.com/it/u=2869268957,1721811479&fm=193&f=GIF')
import type { UploadInstance } from 'element-plus'

let isflag = ref(false)
const dialogFormVisible = ref(false)
const uploadRef = ref<UploadInstance>()
const input = ref('')
const uploadurl=import.meta.env.VITE_API_URL + 'upload'

//游行标签
import { ElInput } from 'element-plus'
const inputValue = ref('')
const dynamicTags = ref<string[]>([])
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

// 定义关闭标签的处理函数
const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'

let $router = useRouter()
// 接收路由传递的参数
const $route = useRoute()
const encodedObject = $route.query.item
//console.log(encodedObject)

const item = ref()
if (encodedObject) {
  const newItem = JSON.parse(decodeURIComponent(encodedObject as string))
  //console.log(newItem);
  
    item.value = newItem
}
const contents = ref('')
onMounted(() => {
  if (item.value) { //更新
    isflag.value = true  
    imageUrl.value = item.value.img
    formInline.date = item.value.date
    input.value = item.value.title
    formInline.people = item.value.people
    formInline.money = item.value.money
    formInline.num = item.value.num
    dynamicTags.value = [...item.value.tag]
    contents.value = item.value.content
  }
})
//完成游记
const gofinish = async (content: string) => {
  if (
    input.value &&
    formInline.date &&
    formInline.people &&
    formInline.money &&
    formInline.num &&
    content &&
    dynamicTags.value.length
  ) {
    if(!isflag.value) goadd(content)
    else goupdate(content)
  } else {
    ElMessage({
      message: '仍有其他信息还未填写，请补充后再完成哦！',
      type: 'warning'
    })
  }
}
const goadd=async(content:string)=>{
  const data={
      title: input.value,
      date: formInline.date,
      people: formInline.people,
      money: formInline.money,
      content: content,
      tag: JSON.stringify(dynamicTags.value),
      num: formInline.num,
      img: imageUrl.value,
      author: useStore.username
    }
  let result:reqtype = await write(data)
  if (result.status == 0) {
      ElMessage({
        message: '发表游记成功！',
        type: 'success'
      })
    }

    $router.push('/strategy/travelstrategy') // 返回上一页
}

const goupdate=async(content:string)=>{
  let result:reqtype = await update({
      title: input.value,
      date: formInline.date,
      people: formInline.people,
      money: formInline.money,
      content: content,
      tag: JSON.stringify(dynamicTags.value),
      num: formInline.num,
      img: imageUrl.value,
      author: useStore.username,
      id:item.value.id
    })
  if (result.status == 0) {
      ElMessage({
        message: '游记更新成功！',
        type: 'success'
      })
    }
    isflag.value=false
    $router.push('/mycollect') // 返回上一页
}
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

const formInline = reactive({
  date: '',
  people: 0,
  money: 0,
  num: 1
})
// 图片上传成功返回图片地址
const handleAvatarSuccess = (res:any) => {
  // 如果上传成功
  if (res) {
    imageUrl.value = res.imagePath
  } else {
    ElMessage({
      message: '提交失败！',
      type: 'error'
    })
  }
}
</script>

<style scoped>
.set_page {
  /* 根组件样式 */
  width: 100%;
  position: relative;
  height: 100vh; /* 设置组件高度为视口高度 */
  .head {
    .upload-demo {
      /* 上传组件样式 */
      width: 100%;
      height: 500px;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      z-index: 1;
    }
    img {
      position: absolute;
      top: 0;
      left: 0;
      /* 头像图片样式 */
      width: 100%; /* 宽度为父容器宽度 */
      height: 500px; /* 高度自动，保持图片纵横比 */
      /* max-height: 500px; 最大高度限制为500px */
      /* object-fit: cover; 图片覆盖整个容器，保持纵横比 */
    }
    .input {
      position: absolute;
      top: 81%;
      left: 36%;
    }
    .avatar {
      position: absolute;
      top: 80%;
      left: 30%;
    }
  }
}

.set {
  /* 设置部分的样式 */
  position: absolute;
  top: 30%;
  left: 53%;
  color: #7c7877;
  font-size: 15px;
  h2 {
    color: black;
    font-size: 18px;
    margin-bottom: 5px;
  }
}
.main {
  margin-top: 50px;
}

.input >>> .el-input__inner {
  font-size: 18px !important;
  color: #000000 !important;
  font-family: cursive !important;
  height: 50px;
}
</style>
